package com.cardgame.model.level;

import com.cardgame.model.card.RoleCard;
import com.cardgame.model.card.RoleWeaponCard;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


// 场上角色战斗状态封装类
public class LevelRole {
    @Getter
    private final RoleCard role;
    private int currentHP;
    @Getter
    private RoleWeaponCard weapon;
    @Getter
    private final List<LevelBuff> buffs;
    @Getter
    @Setter
    private boolean isFirstShow = true;
    @Getter
    @Setter
    private boolean isHurt = false;

    public LevelRole(RoleCard role) {
        this.role = role;
        this.currentHP = role.getHealth();
        this.weapon = null;
        this.buffs = new ArrayList<>();
    }

    public void addBuff(LevelBuff buff) {
        buffs.add(buff);
    }

    public void setWeapon(RoleWeaponCard weapon) {
        this.weapon = weapon;
        this.currentHP += weapon.getAddHPMax();
    }

    public int getMaxHP() {
        return role.getHealth() + (weapon != null ? weapon.getAddHPMax() : 0);
    }

    public int getAttack(){
        int attack = role.getAttack();
        if (weapon != null)
            attack += weapon.getAddAttack();
        for (LevelBuff buff : buffs) {
            switch (buff.getBuff().getBuffEffectType()){
                case ATTACK_BOOST -> attack += buff.getBuff().getBuffValue();
                case ATTACK_REDUCE -> attack -= buff.getBuff().getBuffValue();
            }
        }
        return Math.max(attack, 0);
    }

    /*
     * @param damage 受到的伤害
     * @return 是否死亡
     */
    public boolean getAttacked(int damage){
        currentHP -= damage;
        isHurt = true;
        return currentHP <= 0;
    }

    public void heal(int heal){
        currentHP += heal;
        if (currentHP > getMaxHP())
            currentHP = getMaxHP();
    }

    /*
     *
     * buff生效
     * @return 是否死亡
     */
    public boolean buffEffect(){
        for (LevelBuff buff : buffs) {
            switch (buff.getBuff().getBuffEffectType()){
                case HP_BOOST -> heal(buff.getBuff().getBuffValue());
                case HP_REDUCE -> getAttacked(buff.getBuff().getBuffValue());
                default -> {}
            }
            buff.setDuration(buff.getDuration() - 1);
        }
        buffs.removeIf((buff) -> buff.getDuration() <= 0);
        return currentHP <= 0;
    }

    public Map<String, Object> toMap() {
        Map<String, Object> map = role.toMap();
        map.put("currentHp", currentHP);
        map.put("maxHP", getMaxHP());
        map.put("currentAttack", getAttack());
        map.put("isFirstShow", isFirstShow);
        map.put("isHurt", isHurt);
        map.put("weapon", weapon!= null? weapon.toMap() : null);
        map.put("buffs", buffs.stream().map(LevelBuff::toMap).toList());
        isFirstShow = false;
        isHurt = false;
        return map;
    }
}
